<template>
    <view flex class="dingbu text-center">
        <view
            @click="clickTab(index)"
            :class="`px-2 py-10px w-50px shrink-0 tab ${activeIndex === index ? 'activeTab' : ''}`"
            v-for="(item, index) in tabList"
        >
            {{ item.title }}
        </view>
    </view>

    <scroll-view scroll-y @scrolltolower="onScrollToLower" class="orderList">
        <view @click="clickOrder(item.orderNo)" p-5 m-14px class="geshi" v-for="item in orderList">
            <view flex class="dingdanhao">
                <view flex class="color-#666 text-xs">
                    <view>订单号:</view>
                    <view ml-2>{{ item.orderNo }}</view>
                </view>
                <view class="color-red-7"> {{ getStatusText(item.status) }} </view>
            </view>
            <view style="border-bottom: 1px solid #eee" v-for="item1 in item.orderItems">
                <view flex mt-4>
                    <image class="h-100px w-100px shrink-0" :src="item1.spuImg" />
                    <view class="flex-grow">
                        <view ml-4>{{ item1.skuName }}</view>
                        <view mt-2 mb-2 ml-4 color-coolgray>{{ formatSpecifications(item1.specifications) }}</view>
                        <view flex justify-between class="mt-3">
                            <view color-red-7 class="font-bold ml-4">￥{{ item1.price }}</view>
                            <view class="flex items-center"><wd-icon name="close-normal" size="22px"></wd-icon>{{ item1.quantity }}</view>
                        </view>
                    </view>
                </view>
                <view class="flex justify-end my-2" @click.stop>
                    <wd-button type="info" @click="clickRefund(item1.orderNo)" v-if="item.status === 1 || item.status === 2" size="small"
                        >退款</wd-button
                    >
                </view>
            </view>
            <view flex justify-between mt-2>
                <view flex>
                    共{{ calcTotal(item.orderItems) }}件商品 合计:
                    <view class="font-bold color-red-7 ml-1">￥{{ calcPrice(item.orderItems) }}</view>
                </view>
                <view @click.stop>
                    <wd-button
                        custom-style="margin-right: 6px!important;"
                        @click="clickPay(item.orderNo, item.orderItems)"
                        v-if="item.status === 0"
                        size="small"
                        >付款</wd-button
                    >
                    <wd-button class="cancelBtn" @click="handleCancel(item.orderNo)" v-if="item.status === 0" type="info" size="small"
                        >取消</wd-button
                    >
                </view>
            </view>
        </view>
        <view class="no-more" v-if="noMore">没有更多数据了</view>
    </scroll-view>
    <wd-toast />
    <wd-message-box selector="message" />
    <PayOrder ref="payOrderRef" :orderNo="payOrderNo" :orderItems="payOrderItems" />
    <wd-message-box selector="wd-message-box-slot">
        <wd-textarea v-model="refundReason" placeholder="请输入退款原因" maxlength="200" show-word-limit></wd-textarea>
    </wd-message-box>
</template>

<script setup>
import { ref } from "vue";
import { cancelOrder, getOrderList, refundOrder } from "@/api/order";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { useMessage, useToast } from "wot-design-uni";
import PayOrder from "../../components/PayOrder.vue";

const orderList = ref([]);

const formatSpecifications = specifications => {
    let str = "";
    let obj = {};
    specifications.forEach(item => {
        obj = {
            ...obj,
            ...item,
        };
    });
    for (const key in obj) {
        str += `,${key}:${obj[key]}`;
    }
    str = str.slice(1, str.length);
    return str;
};

const calcTotal = orderItems => {
    let total = 0;
    orderItems.forEach(item => {
        total += item.quantity;
    });
    return total;
};
const calcPrice = orderItems => {
    let price = 0;
    orderItems.forEach(item => {
        price += item.price * item.quantity;
    });
    return price;
};
const tabList = ref([
    {
        title: "全部",
    },
    {
        title: "待支付",
    },
    {
        title: "待发货",
    },
    {
        title: "待收货",
    },
    {
        title: "已完成",
    },
    {
        title: "已取消",
    },
    {
        title: "退款中",
    },
    {
        title: "已退款",
    },
]);
const getStatusText = status => {
    return tabList.value[status + 1].title;
};
const activeIndex = ref(0);
let status;
const clickTab = index => {
    activeIndex.value = index;
    page = 1;
    noMore.value = false;
    orderList.value = [];
    if (index === 0) {
        status = undefined;
        return fetchList();
    }
    status = index - 1;
    fetchList(index - 1);
};

let page = 1;
let pageSize = 10;
let total = 0;
const noMore = ref(false);
const fetchList = async status => {
    if (noMore.value) return;
    const params = {
        page,
        pageSize,
    };
    if (status !== undefined) params.status = status;
    const res = await getOrderList(params);
    orderList.value = [...orderList.value, ...res.data.list];
    if (orderList.value.length === res.data.total) noMore.value = true;
};
const onScrollToLower = () => {
    page++;
    if (activeIndex.value === 0) return fetchList();
    fetchList(activeIndex.value - 1);
};

onLoad(e => {
    if (e.status === undefined) {
        activeIndex.value = 0;
    } else {
        activeIndex.value = +e.status + 1;
    }
    status = e.status;
});
const resetPage = () => {
    page = 1;
    noMore.value = false;
    orderList.value = [];
};
onShow(() => {
    resetPage();
    fetchList(status);
});
const toast = useToast();
const message = useMessage("message");
const handleCancel = async orderNo => {
    await message.confirm("确定取消订单吗?");
    await cancelOrder(orderNo);
    toast.success("取消成功");
    orderList.value = [];
    page = 1;
    if (activeIndex.value === 0) {
        fetchList();
    } else {
        fetchList(activeIndex.value - 1);
    }
};
const clickOrder = orderNo => {
    uni.navigateTo({
        url: `/pages/orderDetail/orderDetail?orderNo=${orderNo}`,
    });
};
const payOrderNo = ref("");
const payOrderItems = ref([]);
const payOrderRef = ref();
const clickPay = (orderNo, orderItems) => {
    payOrderNo.value = orderNo;
    payOrderItems.value = orderItems;
    payOrderRef.value.open();
};
const refundReason = ref("");
const refundMessage = useMessage("wd-message-box-slot");
const clickRefund = async orderNo => {
    console.log("退款");
    await refundMessage.confirm({
        title: "确认退款",
        beforeConfirm: async ({ resolve }) => {
            await refundOrder({
                orderNo,
                refundReason: refundReason.value,
            });
            toast.success("退款成功");
            resetPage();
            activeIndex.value = 0;
            fetchList();
            resolve(true);
        },
    });
};
</script>

<style>
.dingbu {
    width: 100vw;
    padding: 0 14px;
    height: 50px;
    justify-content: space-between;
    align-items: center;
    background-color: white;
    color: #666;
    box-sizing: border-box;
    overflow: scroll;
}

.geshi {
    width: calc(100% - 28px);
    background-color: white;
    border-radius: 10px;
    box-sizing: border-box;
}

.dingdanhao {
    width: 100%;
    justify-content: space-between;
    border-bottom: 1px solid #eee;
    padding-bottom: 15px;
}

.tab {
    border-bottom: 4px solid transparent;
}

.tab + .tab {
    margin-left: 10px;
}

.activeTab {
    border-bottom: 4px solid #1989fa;
}

.orderList {
    height: calc(100vh - 50px - var(--status-bar-height));
}

.no-more {
    text-align: center;
    padding: 16px 0;
    color: #999;
    font-size: 14px;
}

.cancelBtn {
    margin-left: 8px !important;
}
</style>
